package com.google.code.ptrends.common.entities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Session {
	private int id;
	private EventType state;
	private Date startDate;
	private Date endDate;
	private int itemsCount;
	private int supplierID;
	private List<SessionEvent> events;
	
	public Session() {
		state = EventType.OK;
		events = new ArrayList<SessionEvent>();
		startDate = Calendar.getInstance().getTime();
		itemsCount = 0;
	}

	public void clearEvents() {
		getEvents().clear();
	}

	public void increaseItemsCount(int itemsCount) {
		this.itemsCount += itemsCount;
	}

	public void addEvent(final String name, final String description,
			final EventType status) {
		final SessionEvent event = new SessionEvent();
		event.setDescription(description);
		event.setStatus(status);
		event.setName(name);
		event.setEventDate(Calendar.getInstance().getTime());
		getEvents().add(event);
	}

	public void addEvent(final String name, final EventType status) {
		addEvent(name, "", status);
	}

	public void addEvent(SessionEvent event){
		this.events.add(event);
	}
	
	public int getId() {
		return id;
	}

	public void setId(final int id) {
		this.id = id;
	}

	public int getSupplierID() {
		return supplierID;
	}

	public void setSupplierID(int supplierID) {
		this.supplierID = supplierID;
	}

	public void setState(final EventType state) {
		this.state = state;
	}

	public EventType getState() {
		return state;
	}

	public void setStartDate(final Date startDate) {
		if (startDate == null) {
			throw new IllegalArgumentException(
					"Illegal null-reference startDate");
		}

		this.startDate = new Date(startDate.getTime());
	}

	public Date getStartDate() {
		return startDate == null ? null : new Date(startDate.getTime());
	}

	public void setEndDate(final Date endDate) {
		if (endDate == null) {
			throw new IllegalArgumentException("Illegal null-reference endDate");
		}

		this.endDate = new Date(endDate.getTime());
	}

	public Date getEndDate() {
		return endDate == null ? null : new Date(endDate.getTime());
	}

	public void setItemsCount(final int itemsCount) {
		this.itemsCount = itemsCount;
	}

	public int getItemsCount() {
		return itemsCount;
	}

	public Date getDuration() {
		long diff = 0;
		if (startDate != null && endDate != null) {
			diff = endDate.getTime() - startDate.getTime();
		}
		return new Date(diff);
	}

	public List<SessionEvent> getEvents() {
		return events;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (SessionEvent event : events) {
			sb.append(String.format("[%s] %s", event.getEventDate(),
					event.getName()));
			sb.append("\n");
		}

		return sb.toString();
	}
}
